package com.cola.xml;

import jdk.swing.interop.LightweightFrameWrapper;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @Grup:com.cola.xml
 * @Auther:cola
 * @Data:2021/4/10-2021-04-12:17
 * @version:1.0
 */
public class personHandler extends DefaultHandler {
    private List<person> persons=null;
    private person p;//当前正在解析的person

    private  String tag;//用于记录正在解析的标签名
    //开始解析文档时调用
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        persons=new ArrayList<>();
        System.out.println("开始解析文档");
    }
    //在XML文档解析结束时调用
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("解析文档结束!");
    }

    //解析开始元素时调用
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        if("person".equals(qName)){
            p=new person();
            String personid = attributes.getValue("personid");
            p.setPersonid(personid);
        }
        tag=qName;
    }

    public List<person> getPersons() {
        return persons;
    }

    //解析结束元素调用
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        if ("person".equals(qName)){
            persons.add(p);
        }
        tag=null;
    }
    //解析文本内容时调用
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        if (tag!=null){
            if ("name".equals(tag)){
                p.setName(new String(ch,start,length));
            }else if ("address".equals(tag)){
                p.setAddress(new String(ch,start,length));
            }else if ("tel".equals(tag)){
                p.setTel(new String(ch,start,length));
            }else if ("fax".equals(tag)){
                p.setFax(new String(ch,start,length));
            }else if ("email".equals(tag)){
                p.setEmail(new String(ch,start,length));
            }
        }
    }
}
